// src/contexts/AuthContext.tsx
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import request, { getMacAddress } from '../utils/request';

interface AuthContextType {
  isLogin: boolean;
  isLoading: boolean;
  username: string | null;
  login: (username: string, password: string) => Promise<any>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [isLogin, setIsLogin] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [username, setUsername] = useState<string | null>(null);

  useEffect(() => {
    const token = localStorage.getItem('token');
    const savedUsername = localStorage.getItem('username');
    if (token) {
      setIsLogin(true);
      setUsername(savedUsername);
      
      // 设置后端的 API token
      try {
        const { ipcRenderer } = window.require('electron');
        ipcRenderer.invoke('set-api-token', token).catch((error: any) => {
          console.warn('Failed to set backend API token on init:', error);
        });
      } catch (error) {
        console.warn('Failed to set backend API token on init:', error);
      }
    }
    setIsLoading(false);
  }, []);

  // 定义登录响应数据的类型
  interface LoginResponseData { 
    token: string; 
  }
  
  // 修改 login 方法，接收 username 和 password
  const login = async (username: string, password: string) => { 
    try { 
      // 获取MAC地址
      const macAddress = await getMacAddress();
      
      const res = await request.post<LoginResponseData>("login", { 
        username, 
        password,
        macAddress: macAddress || undefined // 如果获取不到MAC地址，则不发送该字段
      }); 
      if (res.code === 0) { 
        setIsLogin(true); 
        setUsername(username);
        localStorage.setItem('token', res.data.token); 
        localStorage.setItem('username', username);
        request.setToken(res.data.token); // 确保后续请求自动带token
        
        // 设置后端的 API token
        try {
          const { ipcRenderer } = window.require('electron');
          await ipcRenderer.invoke('set-api-token', res.data.token);
        } catch (error) {
          console.warn('Failed to set backend API token:', error);
        }
        
        return res; 
      } 
    } catch (error) { 
      throw new Error('登录失败，响应格式不正确'); 
    } 
  };

  const logout = () => {
    setIsLogin(false);
    setUsername(null);
    localStorage.removeItem('token');
    localStorage.removeItem('username');
  };

  return (
    <AuthContext.Provider value={{ isLogin, isLoading, username, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};